<template>
    <div class="online-process full-height scrollbar padding-t-10">
      <div class="margin-l-20 flex items-center" style="height: 36px">
        <q-btn flat
               :color="onlineType === 1 ? 'primary' : '#eee'"
               class="table-flat-btn"
              @click="onlineType = 1">
          实时参数
        </q-btn>
        <div class="qh-line margin-l-10 margin-r-10" style="height: 16px"></div>
        <q-btn flat
               :color="onlineType === 2 ? 'primary' : '#eee'"
               class="table-flat-btn"
               @click="onShowLine">
          实时曲线
        </q-btn>
      </div>
      <div v-show="onlineType === 1">
        <div class="padding-20" style="padding-bottom:10px; padding-top:10px">
          <!-- 路径 -->
          <div class="online-path flex justify-center">
            <q-btn
              flat
              round
              icon="iconfont icontubiao-44"
              @click="toPathOne"
              class="q-mr-sm"
            />
            <div class="flex" style="padding-top:5px">
              <div
                v-for="(item, index) in pathBtn"
                :key="index"
                v-ripple
                @click="onPathTo(item)"
                :class="item.isCheck ? 'check-div' : 'not-check-div '"
                class="q-mr-sm text-center"
              >
                {{ item.label }}
              </div>
            </div>
            <q-btn flat round icon="iconfont icontubiao-43" @click="toPathTwo" />
          </div>
          <!-- 数控系统： -->
          <div class="online-title margin-b-10">
            数控系统：{{ queryParams.ncType || "--" }}
          </div>
          <!-- 实时数据信息 -->
          <div class="flex">
            <div style="width: 280px;min-width: 280px" class="margin-r-20">
              <online-card
                :titleList="['实时信息']"
                class="margin-b-20"
                :height="230"
              >
                <template slot="content">
                  <div class="flex" v-for="(v, index) in processMq" :key="index">
                    <div class="more-title text-center">{{ v.label }}</div>
                    <div class="more-title text-center">
                      {{ v.value }}{{ v.unit }}
                    </div>
                  </div>
                  <div class="flex" v-for="v in realList" :key="v.value">
                    <div class="more-title text-center">{{ v.value }}</div>
                    <div class="more-title text-center text-ellipsis q-pr-sm">
                      {{
                        (v.label === "program"
                          ? setProcessProgram(processMessage.program)
                          : processMessage[v.label]) || "--"
                      }}{{ v.unit }}
                      <q-tooltip>
                        {{
                          (v.label === "program"
                            ? setProcessProgram(processMessage.program)
                            : processMessage[v.label]) || "--"
                        }}{{ v.unit }}
                      </q-tooltip>
                    </div>
                  </div>
                </template>
              </online-card>
              <online-card :titleList="['统计信息']" :height="150">
                <template slot="content">
                  <div class="flex" v-for="v in statisticalList" :key="v.value">
                    <div class="more-title text-center">{{ v.value }}</div>
                    <div class="more-title text-center">
                      {{ statistics[v.label] }}
                    </div>
                  </div>
                </template>
              </online-card>
            </div>
            <online-card
              :titleList="['伺服轴', '机械坐标']"
              :height="400"
              style="width: 280px;min-width: 280px"
              class="margin-r-20"
            >
              <template slot="content">
                <div
                  class="flex margin-b-10"
                  v-for="(v, index) in proBt"
                  :key="index"
                >
                  <div class="m-title text-center text-ellipsis">{{ v.label }}</div>
                  <div class="m-title text-center text-ellipsis">{{ v.value }}</div>
                  <q-tooltip>{{ v.label }} : {{ v.value }}</q-tooltip>
                </div>
              </template>
            </online-card>
            <div style="width: calc(100% - 600px); min-width: calc(100% - 600px)">
              <online-card
                :titleList="['报警信息']"
                :height="400"
                :isCardType="false"
              >
                <template slot="header">
                  <div>
                    <q-icon
                      class="iconfont icontubiao-78 font-size-16"
                      style="vertical-align: top;color: #E43434 ;"
                    />
                    <span class="font-size-16" style="color: #E43434">
                      {{ policeLength }}条
                    </span>
                  </div>
                </template>
                <template slot="content">
                  <callPolice ref="callP" @isShowPolice="onShowPolice" />
                </template>
              </online-card>
            </div>
          </div>
        </div>
        <div class="margin-r-20 margin-l-20">
          <online-card
            :titleList="['自定义参数']"
            :isCardType="false"
            :height="220"
          >
            <template slot="header">
              <div>时间戳: {{ userList.date || "--" }}</div>
            </template>
            <template slot="content">
              <div
                style=" word-break: break-word;"
                class="scrollbar overflow-auto full-height"
              >
                <div
                  class="flex justify-around"
                  style="border-bottom: 1px solid #eee; line-height:40px"
                >
                  <div style="width:12%;margin-left: 16px">序号</div>
                  <div style="width:40%">参数名</div>
                  <div style="width:42%">参数值</div>
                </div>
                <div class="overflow-auto scrollbar" style="height:68px">
                  <div
                    class="flex justify-around"
                    v-for="(item, index) in userList.list"
                    :key="index"
                  >
                    <div style="width:12%; word-break: break-word">
                      {{ index + 1 }}
                    </div>
                    <div style="width:40%; word-break: break-word">
                      {{ item.value }}
                    </div>
                    <div style="width:42%; word-break: break-word">
                      {{ item.label }}
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </online-card>
        </div>
      </div>
      <div  v-show="onlineType === 2">
        <q-tabs
          v-model="tab"
          shrink
          stretch
          dense
          inline-label
          align="left"
          active-color="primary"
          indicator-color="primary"
        >
          <q-tab
            :name="item.value"
            v-for="(item, index) in allBtn"
            :key="index"
            :label="item.label"
          />
        </q-tabs>
        <q-separator class="full-width line" />
        <div class="all-echart">
          <div class="item-echart" v-show="setEchartShow(1)">
            <div style="width: 100%; height: 100%" ref="eChart1"></div>
          </div>
          <div class="item-echart" v-show="setEchartShow(2)">
            <div style="width: 100%; height: 100%" ref="eChart2"></div>
          </div>
          <div class="item-echart" v-show="setEchartShow(3)">
            <div style="width: 100%; height: 100%" ref="eChart3"></div>
          </div>
          <div class="item-echart" v-show="setEchartShow(4)">
            <div style="width: 100%; height: 100%" ref="eChart4"></div>
          </div>
          <div class="item-echart" v-show="setEchartShow(5)">
            <div style="width: 100%; height: 100%" ref="eChart5"></div>
          </div>
          <div class="item-echart" v-show="false">
            <div style="width: 100%; height: 100%" ref="eChart6"></div>
          </div>
          <div class="item-echart" v-show="setEchartShow(7)">
            <div style="width: 100%; height: 100%" ref="eChart7"></div>
          </div>
        </div>
      </div>
    </div>
</template>

<script>
import _ from 'lodash'

import onlineCard from './components/online-process/online-card'
import ONLINEECHARTS from './components/online-process/get-online-echarts'
import ONBARECHARTS from './components/online-process/get-bar-echarts'
import {
  getCurrentWorkpieces,
  sendMsg,
  sendUatMsg
} from '../../boot/status-monitor/machine.js'
import {
  numberToChinese,
  RealtimeProcessingDataMsgParser,
  secondToString
} from 'src/assets/js/util'
import { mapGetters } from 'vuex'
import callPolice from './components/online-process/call-police'
import ONLINEPROCESS from './components/online-process/online-process.js'
import echarts from 'echarts'

export default {
  name: 'online-process',
  components: {
    callPolice,
    onlineCard
  },
  mixins: [ONLINEPROCESS],
  data () {
    return {
      onlineType: 1, //  1： 实时参数 2：实时曲线
      lengthPth: 1, // 长度问题
      pathBtn: [], // 路径按钮集合
      timerSend: null,
      queryParams: {},
      chart: null,
      processMessage: {}, // 接受到盒子返回信息
      processMes: [], // 接受到盒子返回信息
      msgParser: null,
      // 移动距离:
      switchSingleStep: 240,
      yPos: 0,
      // chart 集合
      chartData: [],
      // 程序的E chart单独处理.
      chartBarData: {},
      // 统计
      statistics: {
        currentCount: '--',
        lastCycle: '--',
        thisCycleStartTime: '--'
      },
      timerTime: null,
      proMesValue: 0,
      startTime: '',
      // call police
      policeLength: 0, // 报警条数
      tab: 0,
      // 用户自定义数据
      userData: '',
      userUatSendMsg: null,
      // 实时信息显示字段形式
      realList: [
        {
          value: 'F速度',
          label: 'path_feedrate',
          unit: 'mm/min'
        },
        {
          value: 'F倍率',
          label: 'Fovr',
          unit: '%'
        },
        {
          value: '刀具号',
          label: 'tool_id',
          unit: ''
        },
        {
          value: '程序号',
          label: 'program',
          unit: ''
        }
      ],
      // 统计信息显示字段.
      statisticalList: [
        {
          value: '当日计数',
          label: 'currentCount'
        },
        {
          value: '上次循环',
          label: 'lastCycle'
        },
        {
          value: '本次循环',
          label: 'thisCycleStartTime'
        }
      ]
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'client']),
    // 解析轴承
    proBt () {
      return this.getActList()
    },
    // 一个路径下多个S主轴
    processMq () {
      return this.getMoreSpeed()
    },
    // 动画效果
    pos () {
      return {
        transform: `translate(0px,${this.yPos}px)`,
        transition: `all 2ms`,
        overflow: 'hidden'
      }
    },
    userList () {
      const str = '|'
      const params = {
        date: null,
        list: []
      }
      if (this.userData.includes(str)) {
        const arr = this.userData.split(str)
        params.date = arr[0]
        let newArr = _.tail(arr)
        for (let i = 0; i < newArr.length; i += 2) {
          const value = newArr[i]
          const label = newArr[i + 1]
          params.list.push({ label, value })
        }
      } else {
        params.date = this.userData
      }
      return params
    }
  },
  props: {
    processData: Object
  },
  watch: {
    processData: {
      handler (val) {
        if (!_.isEmpty(val)) {
          this.queryParams = _.cloneDeep(val)
          this.processMessage = {}
          this.processMes = []
          this.userData = ''
          this.initCheckBtn()
          this.clearEchart()
          this.timerSend && clearInterval(this.timerSend)
          const _self = this
          this.$nextTick(() => {
            this.setBarEchart()
            this.setEchart()
            _self.onSelectPath(_self.proMesValue + 1)
            this.timerSend = setInterval(() => {
              _self.onSelectPath(_self.proMesValue + 1)
            }, 60000) // 定时请求
            this.onSubscribe()
            this.$refs.callP.getMachineStatusDetails(this.queryParams)
            this.getCurrentWorkpieces(this.queryParams)
          })
        }
      },
      immediate: true,
      deep: true
    },
    $route: {
      handler (val) {
        this.queryParams.ncType = ''
        this.userData = ''
        this.processMessage = {}
        this.processMes = []
        this.proMesValue = 0
        this.initCheckBtn()
        this.lengthPth = 1
        //  清楚定时绘制
        this.clearEchart()
        this.closeUbscribeTopic()
        this.timerSend && clearInterval(this.timerSend)
        this.timerTime && clearInterval(this.timerTime)
      },
      deep: true
    },
    // 路径变化
    lengthPth: {
      handler (val) {
        this.pathBtn = []
        if (val) {
          for (let i = 1; i <= val; i++) {
            this.pathBtn[i - 1] = {
              label: `路径${numberToChinese(i)}`,
              value: i - 1,
              isCheck: i === 1
            }
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 是否显示报警列表
    onShowPolice (val) {
      this.policeLength = val
    },
    // 动态显示
    setEchartShow (val) {
      if (this.tab === 0) return true
      return this.tab === val
    },
    initCheckBtn () {
      this.tab = 0
    },
    //
    onPathTo (val) {
      const _self = this
      if (this.proMesValue === val.value) return
      this.pathBtn.map(v => {
        v.isCheck = false
      })
      this.clearEchart()
      this.loadMap.clear() // 动态轴数据的输送
      this.pathBtn[val.value].isCheck = true
      // 切换路径
      this.proMesValue = val.value
      this.processMessage = {}
      this.timerSend && clearInterval(this.timerSend)
      this.onSelectPath(val.value + 1)
      setTimeout(() => {
        _self.setBarEchart()
        _self.setEchart()
      })
      this.timerSend = setInterval(() => {
        this.onSelectPath(val.value + 1)
      }, 60000) // 定时请求
    },
    // 向左
    toPathOne () {
      const m = this.pathBtn.find(v => v.isCheck).value
      const params = {
        value: m === 0 ? 0 : m - 1
      }
      this.onPathTo(params)
    },
    // 向右
    toPathTwo () {
      const m = this.pathBtn.find(v => v.isCheck).value
      const params = {
        value: m === this.lengthPth - 1 ? this.lengthPth - 1 : m + 1
      }
      this.onPathTo(params)
    },
    // 返回程序号,,取取小树点前一位
    setProcessProgram (program) {
      if (program) {
        const i = program.indexOf('.')
        return i > -1 ? program.slice(0, i) : program
      } else {
        return '--'
      }
    },
    // 实时
    /**
     * 订阅并发送消息
     */
    onSubscribe () {
      if (this.client) {
        console.log('连接成功')
        const id = this.queryParams.id
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.onlineProcessDetail.subscribeTopic}${id}`,
          this.onMessageArrived,
          { id: `processTopic` }
        )
        // 订阅报警实时信息
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.realTimeStatus.subscribeTopic}${this.queryParams.workshopId}`,
          this.onMessageArrived,
          { id: `realTimeStatus` }
        )
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.normalWorkpiece.subscribeTopic}${id}`,
          this.onMessageArrived,
          { id: `normalWorkpiece` }
        )
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.userdataTopic.subscribeTopic}${id}`,
          this.onMessageArrived,
          { id: `userdataTopic` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    // 访问后台（一分钟）
    sendMsg () {
      sendMsg(this.queryParams.id)
    },
    // 判断是否多路径 return 路径
    isLtPath (val) {
      return val[0]['path'] || val.length || 1
    },
    // 点击路径进行发送订阅消息
    // path 路径 reportType 0全部 1 仅用自定义 2 实时
    onSelectPath (path, reportType = 0) {
      sendUatMsg({
        cmd: 1,
        deviceId: this.queryParams.id,
        reportType,
        path
      })
    },
    /**
     * 接受盒子返回消息
     * @param {string} message
     */
    onMessageArrived (message) {
      let arr = message.headers.destination
      const ret = JSON.parse(message.body).data
      _.includes(arr, 'ACTUAL') && this.onACTUAL(ret) // 实时数据展示
      _.includes(arr, 'realTimeStatus') && this.onRealTimeStatus(ret) // 报警状态显示
      _.includes(arr, 'normal_workpiece') && this.onNormalWorkpiece(ret) // 统计信息消息
      _.includes(arr, 'userdata') && this.onUserdata(ret) // 用户自定义数据展示
    },
    // 实时数据展示
    onACTUAL (data) {
      this.msgParser = new RealtimeProcessingDataMsgParser([])
      const p = this.msgParser.parse(data).filter(v => !_.isEmpty(v))
      this.processMessage = _.isNil(p[0]['path_cur'])
        ? Object.assign({}, this.processMessage, p[this.proMesValue])
        : Object.assign(
          {},
          this.processMessage,
          (p[0]['path_cur'] === (this.proMesValue + 1).toString() && p[0]) ||
              {}
        )
      // 多路径情况
      if (this.lengthPth !== this.isLtPath(p)) {
        this.lengthPth = this.isLtPath(p)
      }
      // 进行E chart绘制
      // 修改传进去的值
      this.chartData.map(v => {
        v.chart._setProcessMsg(this.getMoreSload(v))
      })
      this.chartBarData.map(v => {
        v.chart._setProcessMsg(this.processMessage || {})
      })
    },
    // 报警状态显示
    onRealTimeStatus (data) {
      // 取盒子id相同的设备.
      if (data.deviceId === this.queryParams.id && data.statusCode === 4) {
        if (data.overFlag) {
          this.$refs.callP.getMachineStatusDetails(this.queryParams)
        } else {
          this.$refs.callP.filterData(data)
        }
      }
    },
    // 统计信息消息
    onNormalWorkpiece (data) {
      const params = {
        currentCount: data.currentCount,
        lastCycle: secondToString(data.lastCycle),
        thisCycleStartTime: this.getTime(data.thisCycleStartTime || 0)
      }
      this.startTime = _.cloneDeep(data.thisCycleStartTime || 0)
      if (this.timerTime) {
        clearInterval(this.timerTime)
        this.setTimeEr()
      }
      this.statistics = Object.assign({}, this.statistics, params)
    },
    // 用户自定义数据展示
    onUserdata (data) {
      this.userData = data
    },
    // 计算到现在的时间
    getTime (time) {
      if (time === 0) {
        return 0
      }
      let upDate = new Date(time)
      let now = new Date()
      return secondToString((now.getTime() - upDate.getTime()) / 1000)
    },
    // 绘制线图的E chart
    setEchart () {
      this.chartData = _.slice(this.allBtn, 1, -1)
      this.chartData.map((v, i) => {
        v.chart = new ONLINEECHARTS(
          echarts.init(this.$refs[`eChart${i + 1}`]),
          v,
          this.processMessage
        )
        v.chart._setIntOption()
      })
    },
    // 绘制柱形图,,程序和刀号..
    setBarEchart () {
      this.chartBarData = _.slice(this.allBtn, -1)
      this.chartBarData.map((v, i) => {
        v.chart = new ONBARECHARTS(
          echarts.init(this.$refs.eChart7),
          v,
          this.processMessage
        )
        v.chart._setIntOption()
      })
    },
    // 清楚绘制
    clearEchart () {
      if (_.isEmpty(this.chartData) || _.isEmpty(this.chartBarData)) {
        return
      }
      this.chartData.map((v, i) => {
        v.chart.clearSetint()
      })
      this.chartBarData.map((v, i) => {
        v.chart.clearSetint()
      })
    },
    onShowLine () {
      this.onlineType = 2
      setTimeout(() => {
        this.chartData.map(v => {
          v.chart.charts && v.chart.charts.resize()
        })
        this.chartBarData.map(v => {
          v.chart.charts && v.chart.charts.resize()
        })
      })
    },
    /**
     * 取消订阅
     */
    closeUbscribeTopic () {
      this.client.unsubscribe('processTopic')
      this.client.unsubscribe('realTimeStatus')
      this.client.unsubscribe('normalWorkpiece')
      this.client.unsubscribe('userdataTopic')
    },
    // 查询报工
    getCurrentWorkpieces (val) {
      getCurrentWorkpieces(val).then(res => {
        const ret = res.data
        this.startTime = _.cloneDeep(ret.thisCycleStartTime || 0)
        const member = {
          currentCount: ret.currentCount,
          lastCycle: secondToString(ret.lastCycle),
          thisCycleStartTime: this.getTime(ret.thisCycleStartTime || 0)
        }
        this.statistics = Object.assign({}, this.statistics, member)
        this.setTimeEr()
      })
    },
    setTimeEr () {
      this.timerTime = setInterval(() => {
        this.$set(
          this.statistics,
          'thisCycleStartTime',
          this.getTime(this.startTime)
        )
      }, 1000)
    },
    resizeEchart () {
      window.addEventListener('resize', () => {
        this.chartData.map(v => {
          v.chart.charts && v.chart.charts.resize()
        })
        this.chartBarData.map(v => {
          v.chart.charts && v.chart.charts.resize()
        })
      })
    }
  },
  mounted () {
    this.$bus.$on('onLeftDrawerOpen', res => {
      setTimeout(() => {
        this.chartData.map(v => {
          v.chart.charts.resize()
        })
        this.chartBarData.map(v => {
          v.chart.charts.resize()
        })
      }, 500)
    })
    this.resizeEchart()
  },
  destroyed () {
    //  清楚定时绘制
    this.clearEchart()
    this.closeUbscribeTopic()
    this.timerSend && clearInterval(this.timerSend)
    this.timerTime && clearInterval(this.timerTime)
  }
}
</script>
<style lang="scss" scoped>
.online-process {
  .online-title {
    height: 16px;
    line-height: 16px;
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: bold;
    color: #333333;
  }
  .all-echart {
    width: 100%;
    .item-echart {
      height: 239px;
      text-align: center;
      padding: 5px;
    }
  }
  .online-path {
    height: 40px;
  }
  .not-check-div {
    width: 72px;
    height: 30px;
    line-height: 30px;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;
    cursor: pointer;
  }
  .check-div {
    width: 72px;
    line-height: 30px;
    height: 30px;
    background: #5f77fd;
    border-radius: 6px;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 500;
    cursor: pointer;
    color: #ffffff;
  }
}
</style>
